#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/3/17 10:13
# @Author  : 柳晓飞
# @Site    : 
# @File    : websocket.py
# @Software: PyCharm

#geventwebsocket github
#https://github.com/jgelens/gevent-websocket

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
import jjGlobal.jjGlobal as jjGlob
import game.user as user
import yaml
import protocal


class JjWebSocket:
    def __init__(self,host,port):
        self.websocketServer = WebSocketServer(
            (host, port),
            Resource({'/jjserver': EchoApplication}),
            debug = False
        ).serve_forever()

class EchoApplication(WebSocketApplication):
    def on_open(self):
        print ("Connection opened")

    def on_message(self, message):
        try:
            data = yaml.load(message)
            id = data['id']#协议号
            print("onMessage ", message)
        except Exception, e:
            print Exception, ":", e
            print '收到如下消息异常'
            print message
            return False
        current_client = self.ws.handler.active_client
        if  id > protocal.gameServerProtocal and id < protocal.gameProto:#gameserver
            if jjGlob.gameserver != None:
                jjGlob.gameserver.gameServerHand.onMsg(data,current_client)
        elif id > protocal.gameProto:#game
           if jjGlob.game != None:
               jjGlob.game.gameHand.onMsg(data,current_client)



    def on_close(self, reason):
        current_client = self.ws.handler.active_client
        jjGlob.gameserver.gameServerHand.onClose(current_client)

        print("onClose")








